package com.raft.core.log.entry;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import com.alibaba.com.caucho.hessian.io.HessianOutput;
import com.raft.core.node.NodeEndpoint;

/**添加节点的日志条目
 * @author Ziroom
 *
 */
public class AddNodeEntry extends GroupConfigEntry {

    /**
     * 新节点
     */
    private final NodeEndpoint newNodeEndpoint;

    public AddNodeEntry(int index, int term, Set<NodeEndpoint> nodeEndpoints, NodeEndpoint newNodeEndpoint) {
        super(KIND_ADD_NODE, index, term, nodeEndpoints);
        this.newNodeEndpoint = newNodeEndpoint;
    }

    /**获取新节点
     * @return
     */
    public NodeEndpoint getNewNodeEndpoint() {
        return newNodeEndpoint;
    }

    @Override
	public Set<NodeEndpoint> getResultNodeEndpoints() {
        Set<NodeEndpoint> configs = new HashSet<>(getNodeEndpoints());
        configs.add(newNodeEndpoint);
        return configs;
    }

    @Override
    public byte[] getCommandBytes() {
    	ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
    	HessianOutput hessianOutput = new HessianOutput(byteOutput);
        try {
			hessianOutput.writeObject(this);
		} catch (IOException e) {
			e.printStackTrace();
		}
        return byteOutput.toByteArray();
    }

    @Override
    public String toString() {
        return "AddNodeEntry{" +
                "index=" + index +
                ", term=" + term +
                ", nodeEndpoints=" + getNodeEndpoints() +
                ", newNodeEndpoint=" + newNodeEndpoint +
                '}';
    }

}
